#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
#include "kernel/param.h"

#define MAX_LINE_LEN 512

int main(int argc, char *argv[])
{
  char *cmd_argv[MAXARG];
  int i;

  if (argc < 2) {
    fprintf(2, "usage: xargs <command> [args...]\n");
    exit();
  }

  for (i = 1; i < argc; i++) {
    cmd_argv[i-1] = argv[i];
  }

  char line[MAX_LINE_LEN];
  char *p = line;
  
  while(read(0, p, 1) > 0) {
    if (*p == '\n') {
      *p = 0;

      cmd_argv[argc-1] = line;
      cmd_argv[argc] = 0;

      if (fork() == 0) {
        exec(cmd_argv[0], cmd_argv);
        fprintf(2, "xargs: exec failed\n");
        exit();
      } else {
        wait();
      }
      
      p = line;
    } else {
      if (p - line < MAX_LINE_LEN - 1) {
        p++;
      } else {
        fprintf(2, "xargs: input line too long\n");
        while(read(0, p, 1) > 0 && *p != '\n');
        p = line;
      }
    }
  }

  exit();
}
